package com.hotel.controller;

import com.hotel.mapper.auto.OrdersMapper;
import com.hotel.mapper.auto.RoomMapper;
import com.hotel.mapper.auto.RoomtypeMapper;
import com.hotel.model.auto.Inform;
import com.hotel.model.auto.Orders;
import com.hotel.model.auto.Roomtype;
import org.mybatis.spring.annotation.MapperScan;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
@MapperScan("com.hotel.mapper.auto")
public class ApiController {

    @Resource
    private RoomtypeMapper roomtypeMapper;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @GetMapping("/Roomtype")
    public List<Roomtype> getRoomtype() {
        return roomtypeMapper.selectList(null);
    }

    @GetMapping("/orders")
    public List<Orders> getOrders() {
        return ordersMapper.selectList(null);
    }

    @PostMapping("/buy")
    public boolean buy(@RequestBody Inform inform) {
        System.out.println(inform);
        int RoomtypeId = inform.getId();
        Roomtype Roomtype = roomtypeMapper.selectById(RoomtypeId);
        int store = Roomtype.getStore() - 1;
        if (store < 0) {
            return false;
        }
        Date date = new Date();
        Orders orders = new Orders();
        /*订单id*/
        orders.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        /*订单名称*/
        orders.setName("购买" + Roomtype.getName() + "订单");
        /*用户id*/
        orders.setUserId(inform.getUserId());
        /*入住人*/
        orders.setCheckName(inform.getCheckName());
        /*身份证号*/
        orders.setIdCard(inform.getIdCard());
        /*联系方式*/
        orders.setPhone(inform.getPhone());
        /*入住时间*/
        orders.setFirstDay(inform.getFirstDay());
        /*离店时间*/
        orders.setLastDay(inform.getLastDay());
        /*入住总天数*/
        orders.setNum(inform.getArr());
        /*房间类型id*/
        orders.setRoomtypeId(RoomtypeId);

        /*房间id*/
        int i = roomMapper.PayRoomId(RoomtypeId);
        String roomId = String.valueOf(i);
        orders.setRoomId(roomId);
        roomMapper.PayUpF(i);
        /*支付宝订单号*/
        /*更新时间*/
        /*总价格*/
        orders.setTotal(Roomtype.getPrice().multiply(new BigDecimal(inform.getArr())));
        /*订单状态*/
        /*创建时间*/
        orders.setCreateTime(date);

        Roomtype.setStore(store);
        return ordersMapper.insert(orders) > 0 &&  roomtypeMapper.updateById(Roomtype) > 0;
    }
}
